package the.broccoli.uc.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.joda.time.LocalDateTime;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import the.broccoli.auth.SessionUser;
import the.broccoli.uc.constant.UserTypeEnum;
import the.broccoli.uc.controller.req.WXLoginReq;
import the.broccoli.uc.entity.User;
import the.broccoli.uc.service.dto.TokenDTO;
import the.broccoli.weixin.service.WeiXinService;
import the.broccoli.weixin.service.dto.WXCode2SessionResultDTO;
import the.broccoli.weixin.service.dto.WeiXinLoginReqDTO;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 登录服务类
 */
@Service
public class LoginService {

    @Resource
    private IUserService userService;

    @Resource
    private WeiXinService weiXinService;

    @Resource
    private TokenService tokenService;

    private Integer tenantId = 300006;

    /**
     * 微信登录业务逻辑
     */
    public SessionUser wxLogin(WXLoginReq req) {
        WeiXinLoginReqDTO weiXinLoginReq = new WeiXinLoginReqDTO();
        weiXinLoginReq.setAppType(req.getAppType());
        weiXinLoginReq.setLoginCode(req.getLoginCode());
        weiXinLoginReq.setPhoneNumberCode(req.getPhoneNumberCode());
        WXCode2SessionResultDTO loginCode2Session = weiXinService.getLoginCode2Session(weiXinLoginReq);

        if (loginCode2Session != null) {
//            List<User> dataList = userService.list(new LambdaQueryWrapper<User>()
//                    .eq(User::getTenantId, tenantId)
//                    .eq(User::getOpenId, loginCode2Session.getOpenid())
//            );

            String phoneNumber = "6666";
            if (StringUtils.hasText(req.getPhoneNumberCode())) {
                phoneNumber = weiXinService.getPhoneNumber(req.getAppType(), req.getPhoneNumberCode());
            }

            User user = getByWxOpen(loginCode2Session.getOpenid(), loginCode2Session.getUnionid());
            if (user == null) {
                user = new User();
                user.setCreatedTime(new Date());
                user.setModifiedTime(new Date());
                user.setTenantId(tenantId);
                user.setPhone(phoneNumber);
                user.setUserType(UserTypeEnum.MINI_APP.getCode() + "");
                user.setOpenId(loginCode2Session.getOpenid());
                user.setUnionId(loginCode2Session.getUnionid());
                user.setUserName(StringUtils.hasText(phoneNumber) ? "用户" + phoneNumber.substring(phoneNumber.length() - 4) : "用户昵称");
                user.setLoginExpire(LocalDateTime.now().plusMonths(1).toDate());
                userService.save(user);
            } else {
                userService.update(new LambdaUpdateWrapper<User>()
                        .set(User::getModifiedTime, new Date())
                        .set(User::getPhone, phoneNumber)
                        .set(User::getLoginExpire, LocalDateTime.now().plusMonths(1).toDate())
                        .set(User::getUnionId, loginCode2Session.getUnionid())
                        .set(User::getOpenId, loginCode2Session.getOpenid())

                        .eq(User::getUserId, user.getUserId())
                );
            }

            SessionUser sessionUser = new SessionUser();
            sessionUser.setUserId(user.getUserId());
            sessionUser.setOpenId(loginCode2Session.getOpenid());
            sessionUser.setTenantId(user.getTenantId());
            sessionUser.setUserName(user.getUserName());
            sessionUser.setPhone(phoneNumber);
            sessionUser.setAvatar(user.getAvatar());

            TokenDTO tokenDTO = tokenService.newToken(user.getTenantId(), user.getUserId(), JSON.toJSONString(sessionUser));
            if (tokenDTO != null) {
                sessionUser.setToken(String.valueOf(tokenDTO.getToken()));
            }

            return sessionUser;
        }
        return null;
    }

    private User getByWxOpen(String openId, String unionId) {
        List<User> dataList = userService.list(new LambdaQueryWrapper<User>()
                .eq(User::getTenantId, tenantId)
                .eq(User::getOpenId, openId)
        );
        if (CollectionUtils.isEmpty(dataList)) {
            dataList = userService.list(new LambdaQueryWrapper<User>()
                    .eq(User::getTenantId, tenantId)
                    .eq(User::getUnionId, unionId));
            if (CollectionUtils.isEmpty(dataList)) {
                return null;
            }
        }
        return dataList.get(0);
    }

}
